package com.ctsi.security.manager.impl;

import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.cache.CommUtilCache;
import com.ctsi.commons.util.response.Page;
import com.ctsi.organise.common.api.OrganiseFactoryBean;
import com.ctsi.organise.common.api.OrganiseServiceProxy;
import com.ctsi.organise.common.api.PersonServiceProxy;
import com.ctsi.organise.common.model.Organise;
import com.ctsi.organise.common.model.UserLogin;
import com.ctsi.security.FetchObjIds;
import com.ctsi.security.domain.DataObject;
import com.ctsi.security.exception.ParamNotValideException;
import com.ctsi.security.service.DataObjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 地市管理员数据权限
 */
@Component
public class DishiAdminFetchObjIds implements FetchObjIds {

    private static final Logger logger = LoggerFactory.getLogger(DishiAdminFetchObjIds.class);

    @Autowired
    private PersonServiceProxy personServiceProxy;
    @Autowired
    private OrganiseServiceProxy organiseServiceProxy;
    @Autowired
    private DataObjectService dataObjectService;

    private static final CommUtilCache<String, Set<String>> cacheUserLoginDataIds = new CommUtilCache<>("user.DishiDoTypeAction");

    @Override
    public String getKey() {
        return "platform_dishiadmin";
    }

    @Override
    public Set<String> getDataObjectIdsByCache(String userLoginId, String doTypeId, String action) {
        Set<String> result = cacheUserLoginDataIds.get(userLoginId);
        if (result != null) {
            return result;
        }
        result =Collections.unmodifiableSet( getDataObjectIds(userLoginId, doTypeId, action));
        // 放入缓存
        cacheUserLoginDataIds.put(userLoginId,result);
        return result;
    }


    private String getPartyIdFromLoginId(String userLoginId) {
        if (UtilValidate.isEmpty(userLoginId)) {
            throw new ParamNotValideException("登录用户参数不能为空！");
        }
        UserLogin userLogin = OrganiseFactoryBean.getInstance().getUserLoginProxy().findById(userLoginId);
        if (userLogin == null) {
            logger.error("user :{} no UserLogin",userLoginId);
            throw new ParamNotValideException("登录用户参数不合法，请检查！id:"+userLoginId);
        }
        String partyId = userLogin.getPartyId();
        return partyId;
    }

    public Set<String> getDataObjectIds(final String userLoginId, String doTypeId, String action) {
        Set<String> result = new HashSet<>();
        // 得到当前登录用户对应的独立组织
        String partyId = getPartyIdFromLoginId(userLoginId);
        // 当前登录用户对应的人员Id
        Organise organise = personServiceProxy.getOrganise4User(partyId);
        if (organise != null) {
            List<Organise> organises = (List<Organise>) organiseServiceProxy.findAllOrganDes(organise.getPartyId());
            return organises.stream().map(Organise::getDataObjectId).collect(Collectors.toSet());
        }else{
            logger.info("party id {} ,no Corporate organization",partyId);
        }
        return  result;
    }

    /**
     * 清除缓存
     * @param userLoginId
     */
    public static void removeCache(String userLoginId) {
        if (userLoginId == null) {
            cacheUserLoginDataIds.clear();
        } else {
            cacheUserLoginDataIds.remove(userLoginId);
        }
    }


    @Override
    public Map<String, DataObject> getDataObject(String userLoginId, String doType, String action) {
        throw new RuntimeException("not support method");
    }

    @Override
    public boolean isUserRole() {
        return false;
    }

    @Override
    public List<DataObject> queryDataObject(String typeId, String parent) {
        throw new RuntimeException("not support method");
    }

    @Override
    public Page<DataObject> queryDataObjectPage(String typeId, Map<String, Object> param, int start, int pageSize) {
        throw new RuntimeException("not support method");
    }

    @Override
    public DataObject findDataObjectById(String id, String typeId) {
        throw new RuntimeException("not support method");
    }
}
